import hashlib

from django.shortcuts import render
from models.models.RequestResult import RequestResult as Res
from django.http import HttpResponseRedirect as Response
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse
from models.models import SystemUser


# 登录
@csrf_exempt
def login(request):
    user_name = request.POST.get("user_name")
    user_pass = request.POST.get("user_pass")
    user_pass = hashlib.md5(user_pass.encode()).hexdigest()
    session = request.session
    user = SystemUser.objects.filter(user_name=user_name, user_pass=user_pass).first()
    if user:
        user.user_pass = ""
        session['admin_user'] = user.to_dict()
        return JsonResponse(Res.success(None))
    else:
        return JsonResponse(Res.error(401, '登录认证失败，用户名或密码错误！'))


# 退出登录
def logout(request):
    del request.session['admin_user']
    return Response('/admin')
